package com.example.myapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.BluetoothContext;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleReadResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.inuker.bluetooth.library.utils.UUIDUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;
import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;

public class MainActivity extends AppCompatActivity {

    SearchResult deviceMiniGT;
    BluetoothClient mClient;
    TextView tvLabel;
    //设备序列号
    String strSheBeiNo;
    String strYingjianNo;
    String strRuanJianNo;
    String strHexNo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnScan = findViewById(R.id.btnScan);
        tvLabel = findViewById(R.id.tvLabel);

        BluetoothContext.set(this);
        mClient = new BluetoothClient(this);

        getPermission();

        if (!mClient.isBluetoothOpened()){
            mClient.openBluetooth();
        }


//        mClient = new BluetoothClient(this);
        // 扫描蓝牙
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchRequest request = new SearchRequest.Builder()
                        .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
                        .build();

                mClient.search(request, new SearchResponse() {
                    @Override
                    public void onSearchStarted() {

                    }

                    @Override
                    public void onDeviceFounded(SearchResult device) {
//                        Beacon beacon = new Beacon(device.scanRecord);
                        if (device.getName() != null) {
                            String s = String.format("beacon for  %s %s", device.getName(), device.getAddress());
                            BluetoothLog.v(s);
                            if (device.getName().contains("mini")){
                                deviceMiniGT = device;
                                tvLabel.setText(s);
                            }
                        }
                    }

                    @Override
                    public void onSearchStopped() {

                    }

                    @Override
                    public void onSearchCanceled() {

                    }
                });
            }
        });

        // 连接蓝牙
        Button btnLinkBlue = findViewById(R.id.linkBlue);
        btnLinkBlue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (deviceMiniGT == null) {
                    Toast.makeText(MainActivity.this,"请先扫描蓝牙设备",Toast.LENGTH_SHORT).show();
                    return;
                }

                mClient.connect(deviceMiniGT.getAddress(), new BleConnectResponse() {
                    @Override
                    public void onResponse(int code, BleGattProfile data) {
                        if (code == REQUEST_SUCCESS) {
                            mClient.stopSearch();
                            Toast.makeText(MainActivity.this,"蓝牙连接成功",Toast.LENGTH_SHORT).show();
                            tvLabel.setText(tvLabel.getText() + "\n 蓝牙连接成功");
                        }else{
                            Toast.makeText(MainActivity.this,"蓝牙连接失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                mClient.registerConnectStatusListener(deviceMiniGT.getAddress(), new BleConnectStatusListener() {
                    @Override
                    public void onConnectStatusChanged(String mac, int status) {
                        if (status == STATUS_CONNECTED) {
//                            tvLabel.setText(tvLabel.getText() + "\n 蓝牙连接成功");
                        } else if (status == STATUS_DISCONNECTED) {
                            Toast.makeText(MainActivity.this,"蓝牙断开连接",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        // 查询蓝牙设备序列号
        Button btnReadNo = findViewById(R.id.btnReadNo);
        btnReadNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isSucValidate()){
                    return;
                }

                UUID UID1 = UUID.fromString("0000180A-0000-1000-8000-00805F9B34FB");
                UUID UID2 = UUID.fromString("00002A25-0000-1000-8000-00805F9B34FB");

                mClient.read(deviceMiniGT.getAddress(), UID1, UID2, new BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        if (code == REQUEST_SUCCESS) {
                            String s = new String(data);
                            strSheBeiNo = s;
                            Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                            tvLabel.setText(tvLabel.getText() + "\n 序列号："+s);
                        }
                    }
                });
            }
        });

        // 查询硬件编号
        Button btnYingJian = findViewById(R.id.btnYingJian);
        btnYingJian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isSucValidate()){
                    return;
                }
                UUID UID1 = UUID.fromString("0000180A-0000-1000-8000-00805F9B34FB");
                UUID UID2 = UUID.fromString("00002A27-0000-1000-8000-00805F9B34FB");

                mClient.read(deviceMiniGT.getAddress(), UID1, UID2, new BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        if (code == REQUEST_SUCCESS) {
                            String s = new String(data);
                            strYingjianNo = s;
                            Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                            tvLabel.setText(tvLabel.getText() + "\n 硬件版本号："+s);
                        }
                    }
                });
            }
        });

        // 查询软件编号
        Button btnRuanJian = findViewById(R.id.btnRuanJian);
        btnRuanJian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isSucValidate()){
                    return;
                }
                UUID UID1 = UUID.fromString("0000180A-0000-1000-8000-00805F9B34FB");
                UUID UID2 = UUID.fromString("00002A28-0000-1000-8000-00805F9B34FB");

                mClient.read(deviceMiniGT.getAddress(), UID1, UID2, new BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        if (code == REQUEST_SUCCESS) {
                            String s = new String(data);
                            strRuanJianNo = s;
                            Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                            tvLabel.setText(tvLabel.getText() + "\n 软件版本号："+s);
                        }
                    }
                });
            }
        });

        // 查询检测Hex
        Button btnJianCe = findViewById(R.id.btnJianCe);
        btnJianCe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isSucValidate()){
                    return;
                }
                UUID UID1 = UUID.fromString("A8F93CCB-B9D6-4746-89FA-C2CC0804FC66");
                UUID UID2 = UUID.fromString("10175B2A-AA06-4200-B68C-A28AC752F30F");
                byte[] bytes = {0x01};
                mClient.write(deviceMiniGT.getAddress(), UID1, UID2, bytes, new BleWriteResponse() {
                    @Override
                    public void onResponse(int code) {
                        if (code == REQUEST_SUCCESS) {
                            Toast.makeText(MainActivity.this,"检测指令发送成功",Toast.LENGTH_SHORT).show();
                            tvLabel.setText(tvLabel.getText() + "\n 检测指令发送成功:4秒后返回检测结果");
                        }
                    }
                });

                Timer t = new Timer();
                t.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        getJianCeValue();
                    }
                },4000);

            }
        });

        // 请求接口获取测试结果
        Button btnPost = findViewById(R.id.btnPost);
        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isSucValidate()){
                    return;
                }

                if (strSheBeiNo == null || strYingjianNo == null || strRuanJianNo == null || strHexNo == null){
                    Toast.makeText(MainActivity.this,"请按顺序执行以上按钮操作",Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    strSheBeiNo = URLEncoder.encode(strSheBeiNo,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println(e.getMessage());
                }

                try {
                    strYingjianNo = URLEncoder.encode(strYingjianNo,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println(e.getMessage());
                }

                try {
                    strRuanJianNo = URLEncoder.encode(strRuanJianNo,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println(e.getMessage());
                }

                try {
                    strHexNo = URLEncoder.encode(strHexNo,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println(e.getMessage());
                }

                OkHttpClient client = new OkHttpClient().newBuilder().build();
                Request request = new Request.Builder()
                        .url("http://47.107.174.66:8090/api/v1/calculate?cn=-1&x="+strHexNo+"&sn="+strSheBeiNo+"&hv="+strYingjianNo+"&sv="+strRuanJianNo+"")
                        .method("GET", null)
                        .addHeader("Green-Appid", "9834897289")
                        .build();

                //&gps=lat:30.461208246729413,lng:114.36862285995309,sys:WGS84

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        tvLabel.setText(tvLabel.getText() + "\n 接口返回失败："+e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String res = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvLabel.setText(tvLabel.getText() + "\n 接口返回结果："+res);
                            }
                        });
                    }
                });
            }
        });

    }


    private  void getJianCeValue(){
        UUID UID1 = UUID.fromString("BA44B63A-1A21-435A-B75C-AA69A2974352");
        UUID UID2 = UUID.fromString("A0D64EBA-AD9C-44EA-9E8B-9BBA41B74380");

        mClient.read(deviceMiniGT.getAddress(), UID1, UID2, new BleReadResponse() {
            @Override
            public void onResponse(int code, byte[] data) {
                if (code == REQUEST_SUCCESS) {
                    String s = "";
                    for (byte b : data) {
                        s += b + " ";
                    }
                    Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                    tvLabel.setText(tvLabel.getText() + "\n 检测结果值："+s);
                    String strHex = bytesToHex(data);
                    tvLabel.setText(tvLabel.getText() + "\n 检测结果值16进制："+strHex);
                    strHexNo = strHex;
                }
            }
        });
    }

    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /// 表单验证
    private Boolean isSucValidate(){
        if (deviceMiniGT == null) {
            Toast.makeText(MainActivity.this,"请先扫描蓝牙设备",Toast.LENGTH_SHORT).show();
            return false;
        }
        int status = mClient.getConnectStatus(deviceMiniGT.getAddress());
        if (status != Constants.STATUS_DEVICE_CONNECTED) {
            Toast.makeText(MainActivity.this,"当前尚未连接到蓝牙设备",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }



    /**
     * 解决：无法发现蓝牙设备的问题
     *
     * 对于发现新设备这个功能, 还需另外两个权限(Android M 以上版本需要显式获取授权,附授权代码):
     */
    private final int ACCESS_LOCATION=1;
    @SuppressLint("WrongConstant")
    private void getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            int permissionCheck = 0;
            permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //未获得权限
                this.requestPermissions( // 请求授权
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION},
                        ACCESS_LOCATION);// 自定义常量,任意整型
            }
        }
    }
}